package il.technion.cs236369.database;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHeader;

/**
 * The class that contain all the details to be stored in the database.
 * @author itamar talmi 0396055979 itamar.talmi@gmail.com , ofir haviv 300228921 havivi1986@gmail.com
 *
 */
public class HttpMessageCacheDetails {
	
	/**
	 * The url to be saved. This is the key of the cache table.
	 */
	public String url;
	
	/**
	 * The headers of the request.
	 */
	public String headers;
	
	/**
	 * The body of the request
	 */
	public byte[] body;
	
	/**
	 * The etag of the request.
	 */
	public String etag;
	
	/**
	 * The constructor of the HttpMessageCacheDetails class. Inits new class to be saved in the cache.
	 * @param url - The url of the request.
	 * @param headers - The headers of the response.
	 * @param body - The body of the response.
	 */
	public HttpMessageCacheDetails(String url, Header[] headers, byte[] body){
		this.url = url;
		StringBuilder sb = new StringBuilder();
		String etag = null;
		for (Header header : headers) {
			if(etag == null && header.getName().equals(HttpHeaders.ETAG) ){
				etag = header.getValue();
			}
			sb.append(header.getName()).append(":").append(header.getValue()).append("/r/n");
		}
		this.headers = sb.toString();
		this.body = body;
		this.etag = etag;
	}
	
	/**
	 * The function prepare the response from the saved details.
	 * @param response - The response to fill.
	 */
	public void WriteIntoHttpResponse(HttpResponse response){
		String[] strHeaders = this.headers.split("\r\n");
		for (String headerStr : strHeaders) {
			String[] headerData = headerStr.split(":");
			response.setHeader(new BasicHeader(headerData[0], headerData[1]));
		}
		response.setEntity(new ByteArrayEntity(this.body));
		response.setHeader(new BasicHeader(HttpHeaders.ETAG, this.etag));
	}
	
	/**
	 * The constructor of the HttpMessageCacheDetails class. Inits new class to be saved in the cache.
	 * @param url - The url of the request.
	 * @param headers - The headers of the response.
	 * @param body - The body of the response.
	 * @param etag - The etag of the response.
	 */
	public HttpMessageCacheDetails(String url, String headers, byte[] body, String etag){
		this.url = url;
		this.headers = headers;
		this.body = body;
		this.etag = etag;
	}
}
